
import mixin from '@/service/mixin';
import mixinReadExcel from '@/service/mixin-read-excel';
import mixinWriteExcel from '@/service/mixin-write-excel';
import Pagination from '@/components/pagination';
import alertDialog from '@/components/alert-dialog';
import complaintUserUp from './components/complaintUserUp';

export default {
    name: 'blacklist',
    components: {
        Pagination,
        alertDialog,
        complaintUserUp
    },
    mixins: [mixin, mixinReadExcel, mixinWriteExcel],
    data() {
        return {
            uploadFile:null,
            maxlength:10,
            form: {
                createTime: [],
                phone: '', // 手机号
                cardId: '', // 身份证
                userName: '', // 姓名
                begin:"", // 创建开始时间
                end:'', // 创建结束时间
                operatorId:'',//创建人id
            },
            rules: {
                //
            },
            showUploadDialog: false,
            uploadForm: {
                type: '1',
                phoneList: [],
                userName:'',
                phone: '',
                cardId: '',
                remark: '',
                excelFile: '未选择任何文件', // 接收上传的excel文件名称
                errorMsg: '', // 错误提示
                file:''
            },
            uploadFormRules: {
                type: [
                    { required: true, message: this.$t('verify.plsChoose') }, // 请选择
                ],
                file: [
                    { required: true, message: this.$t('verify.plsImportData') }, // 请导入数据
                ],
                phoneList: [
                    { required: true, message: this.$t('verify.plsImportData') }, // 请导入数据
                ],
                phone: [
                    {required:true, pattern: /^09[0-9]{9}$/, message: this.$t('verify.plsInputCorrectNum'), trigger: 'blur' }, // 请输入0开头的10位数字
                ],
                cardId: [
                    { required:true,pattern: /^[A-Za-z0-9]+$/, message: this.$t('verify.plsInputRightCardId'), trigger: 'blur' }, // 请输入13位数字
                ],
                userName:[{ required: true,pattern:/^[^ ]/, message: this.$t('verify.nameIsNotEmpty')}],
                remark: [
                    { required: true,pattern:/^[^ ]/, message: this.$t('verify.remarkIsNotEmpty') }, // 请输入
                ],
            },
            dataPickerOpt: {
                disabledDate(date) {
                    const today = new Date();
                    today.setHours(0);
                    today.setMinutes(0);
                    today.setMilliseconds(0);
                    today.setSeconds(0);
                    return date.getTime() < today.getTime();
                },
            },
            operatorList: [], // 操作人列表
            showRefuseDialog: false,
            failData: {
                success: 0,
                fail: 0,
                list: [],
            }, // 失败数据列表
        };
    },
    computed: {
        // 禁用上传按钮
        disabledUpload() {
            const { appName, endDate } = this.uploadForm;
            return !appName || !endDate;
        },
    },
    methods: {
        // 获取列表数据
        getTableData(page = this.page) {
            const { phone, cardId, createTime,userName , operatorId } = this.form;
            const params = {
                phone, // 手机号
                cardId, // 身份证
                begin: '', // 创建开始时间
                end: '', // 创建结束时间
                operatorId, // 操作人id，可以多选
                userName, // y用户名
                page: {
                    pageNo: page.currentPage,
                    pageSize: this.page.pageSize,
                },
            };
            if (createTime && createTime.length) {
                params.begin = createTime[0];
                params.end = createTime[1];
            }
            this.$api.blackList.blacklist(params).then(res => {
                const { status, data } = res;
                if ('1' === status && data) {
                    this.tableData = data.list;
                    this.page.recordsTotal = data.page.totalRecord;
                    this.tableMaxHeight = document.body.clientHeight - 18 - 335;
                }
            });
        },
        // 搜索
        search() {
            this.getTableData();
        },
        // 获取操作人列表
        getOperatorList() {
            let user = this.$storage.get('user');
            let {companyName,domain} = user;
            let params = {
                domain:domain,
                company:companyName
            }
            // let params = 
            this.$api.blackList.creators(params).then(res => {
                const { status, data } = res;
                if ('1' === status && data) {
                    this.operatorList = data;
                }
            });
        },
        // 移除
        remove(row) {
            // 确认将该用户移除黑名单？
            this.$confirm(this.$t('common.confirmRemoveBlacklist'), {
                type: 'warning',
            }).then(() => {
                const user = this.$storage.get('user');
                const params = {
                    id: row.id,
                    // creatorId: user.id,
                    // creatorName: user.username,
                };
                this.$api.blackList.remove(params).then(res => {
                    const { status } = res;
                    if ('1' === status) {
                        this.$message.success(this.$t('common.successfulOperation')); // 操作成功
                        this.getTableData();
                    }
                });
            }).catch(() => {});
        },
        // 打开新增黑名单弹框
        showUpload() {
            this.uploadForm.excelFile = this.$t('common.notChooseFile'); // 初始化提示为--未选择任何文件
            this.uploadForm.type = '1';
            this.uploadForm.phoneList = [];
            this.uploadForm.phone = '';
            this.uploadForm.cardId = '';
            this.uploadForm.remark = '';
            this.uploadForm.errorMsg = '';
            this.uploadForm.userName = '';
            this.showUploadDialog = true;
            this.$nextTick(() => {
                const form = this.$refs.uploadForm;
                form && form.clearValidate();
            });
        },
        submitUpload() {
            const form = this.$refs.uploadForm;
            form.validate((val) => {
                if (val) {
                    const user = this.$storage.get('user');
                    const { phone, cardId, remark, phoneList, type ,userName} = this.uploadForm;
                    // 上传数据
                    const params = {
                        remark,
                        company:user.companyName,
                        domain:user.domain
                    };
                    //单挑新增
                    if ('1' === type) {
                        params.operatorId = user.id;
                        params.operatorName = user.username;
                        params.phone = phone;
                        params.cardId = cardId;
                        params.userName = userName;
                        this.$api.blackList.insert(params, { showDefaultError: false }).then(res => {
                            const { status, msg } = res;
                            if ('1' === status) {
                                this.$message.success(this.$t('common.successfulOperation')); // 操作成功
                                this.showUploadDialog = false;
                                this.getTableData();
                            } else {
                                this.$alert(msg, {
                                    type: 'warning',
                                    confirmButtonText: this.$t('common.confirm'),
                                });
                            }
                        });
                    } else if ('2' === type) {
                        //文件上传到日
                        if (phoneList.length === 0) {
                            this.$message.warning(this.$t('verify.plsCheckFile')); // 请检查文件数据
                            return;
                        }
                        if (phoneList.length > 3000) {
                            this.uploadForm.errorMsg = this.$t('verify.maxImportOnce', { count: 3000 }); // 单次导入最多3000个
                            return;
                        }
                        params.creatorId = user.id;
                        params.creatorName = user.username;
                        params.list = phoneList;
                        this.$api.blackList.import(params).then(res => {
                            const { status, data } = res;
                            if ('1' === status) {
                                this.showUploadDialog = false;
                                this.getTableData();
                                this.failData = data; // 缓存上传数据
                                this.showRefuseDialog = true;
                            }
                        });
                        
                        }

                    }
            });
            
        },
        // 打开文件选择
        handleSelectFile() {
            const uploadFile = this.$refs.uploadFile;
            uploadFile.click();
        },
        // 当上传文件时
        handleFileChange(event) {
            const ele = event.target || event.srcElement;
            if (ele.files && ele.files.length) {
                const file = ele.files[0];
                ele.value = '';
                this.uploadForm.excelFile = file.name;
                this.readExcelFile(file, { header: ['phone', 'cardId','userName'] }).then(data => {
                    console.warn(data)
                    const list = [];
                    // const regPhone = /^0\d{9}$/; // 手机号校验正则
                    const regCardId = /^[A-Za-z0-9]+$/; // 身份证校验正则
                    const numReg = /^\d+$/
                    data.forEach((item,index) => {
                        const { phone, cardId ,userName} = item;
                        console.warn(item,index)
                        if (index!=0) {
                            list.push({ phone, cardId,userName});
                        }
                    });
                    this.uploadForm.phoneList = list;
                });
            }
        },
        // 下载模板
        downloadTemplate() {
            window.open('/blacklist.xls');
        },
        // 下载失败数据
        downloadFailData() {
            const { list } = this.failData;
            // 下载失败列表
            const fileName = 'blacklist-' + this.$options.filters.formatDate(new Date(), 'yyyy-MM-dd-hh-mm-ss') + '.xlsx';
            const failData = [];
            list.forEach(item => {
                failData.push({
                    '手机号（09开头11位数）': item.phone,
                    '身份证号': item.cardId,
                    '姓名':item.userName,
                    '导入失败原因':item.remark,

                });
            });
            this.writeExcelFile(failData, fileName);
        },
        // 改变新增方式时，清除校验
        handleUploadTypeChange() {
            const form = this.$refs.uploadForm;
            form && form.clearValidate();
            this.uploadForm.errorMsg = '';
        },
    },
    created() {
        this.getTableData();
        this.getOperatorList();
    },
}
